package com.hs.Lotto;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;

import com.hs.Log.DebugPrint;
import com.hs.SimpleLotteryInfo.R;
import com.hs.http.HttpConn;
import com.hs.util.DisplayUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CheckMyNumbersActivity extends Activity
{
	private final String LOG_TAG = "CheckMyNumbersActivity";
	public static final String INTENT_KEY_LAST_TURN = "lastturn";
	private final String STR_TURN_URL = "http://www.645lotto.net/resultall/%d.asp";
	
	private static final int HANDLER_EVT_ON_TOAST							= 0x00001;
	private static final int HANDLER_EVT_ON_INSERT							= 0x00002;
	private static final int HANDLER_EVT_ON_REFRESH_LIST					= 0x00003;
	private static final int HANDLER_EVT_ON_CHECK_WIN						= 0x00004;
	private static final int HANDLER_EVT_ON_PARSE							= 0x00005;
	private static final int HANDLER_EVT_ON_COMPARE_DONE					= 0x00006;
	
	private EditText m_edtTurn;
	private Button m_btnInput;
	
	private int m_nLastTurn;
	private Context m_cxt;
	
	private ListView m_lstView;
	
	private BtnOnClickListener m_btnListener;
	
	private ArrayList<NumberInfo> m_arrLstInfo;
	private CheckMyNumbersAdapter m_arrAdt;
	private LottoParser m_lParser;
	
	private int m_nSelIdx;
	
	private ProgressDialog m_proDialog;
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checkmynumbersactivity_layout);
        
        m_nLastTurn = getIntent().getIntExtra(INTENT_KEY_LAST_TURN, 0);
        
        init();
    }
	
	public void onResume()
	{
		super.onResume();
	}
	
	public void onPause()
	{
		super.onPause();
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		
	}
	
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
	}
	
	private void init()
	{
		m_edtTurn = (EditText)findViewById(R.id.edt_id_turn);
		m_btnInput = (Button)findViewById(R.id.btn_id_input);
		
		if( m_nLastTurn > 0 )
		{
			m_edtTurn.setHint( new Formatter().format( getString(R.string.str_input_turn_hint) , m_nLastTurn).toString() );
		} // end if( m_nLastTurn > 0 )
		
		m_btnListener = new BtnOnClickListener();
		m_btnInput.setOnClickListener(m_btnListener);
		m_cxt = this;
		
		m_lstView = (ListView)findViewById(R.id.list_id_items);
		m_arrLstInfo = new ArrayList<NumberInfo>();
		
		m_arrAdt = new CheckMyNumbersAdapter(m_arrLstInfo);
		m_lstView.setAdapter(m_arrAdt);
	}
	
	private Handler m_handler = new Handler()
	{
		public void handleMessage(Message _msg)
		{
			int nWhat = _msg.what;
    		
    		switch( nWhat )
    		{
    			case HANDLER_EVT_ON_TOAST:
    			{
    				String str = (String)_msg.obj;
	    			Toast.makeText(m_cxt, str , Toast.LENGTH_SHORT).show();
	    			break;
    			}
    			
    			case HANDLER_EVT_ON_INSERT:
    			{
    				final ArrayList<String> arrLst = (ArrayList<String>)_msg.obj;
    				
    				if( arrLst.size() < 6 )
    				{
    					m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_TOAST, m_cxt.getString(R.string.str_please_insert_all_number)));
    					return;
    				} // end if( arrLst.size() < 6 )
    				
    				final String strTurn = m_edtTurn.getText().toString();
    				
    				NumberInfo nInfo = new NumberInfo(strTurn , arrLst);
					
					m_arrLstInfo.add(nInfo);
					
					m_handler.sendEmptyMessage(HANDLER_EVT_ON_REFRESH_LIST);
    				
    				break;
    			}
    			
    			case HANDLER_EVT_ON_REFRESH_LIST:
    			{
    				m_edtTurn.setText("");
    				m_arrAdt.notifyDataSetChanged();
    				break;
    			}
    			
    			case HANDLER_EVT_ON_CHECK_WIN:
    			{
    				m_proDialog = ProgressDialog.show(m_cxt , "" , "Wait" , true);
    				m_nSelIdx = (Integer)_msg.obj;
    				NumberInfo nInfo = m_arrLstInfo.get(m_nSelIdx);
    				HttpConn hc = new HttpConn(m_cxt, m_handler);
    				hc.getData(new Formatter().format(STR_TURN_URL, Integer.valueOf(nInfo.m_strTurn)).toString());
    				
    				break;
    			}
    			
    			case HttpConn.HTTP_EVT_OK:
    			{
    				String str = (String)_msg.obj;
    				parseLotto(str);
    				break;
    			}
    			
    			case HttpConn.HTTP_EVT_FAIL:
    			{
    				if( m_proDialog != null )
    				{
    					m_proDialog.dismiss();
    				} // end if( m_proDialog != null )
    				
    				String str = (String)_msg.obj;
	    			Toast.makeText(m_cxt, str , Toast.LENGTH_SHORT).show();
    				break;
    			}
    			
    			case HttpConn.HTTP_EVT_EXCEPTION:
    			{
    				if( m_proDialog != null )
    				{
    					m_proDialog.dismiss();
    				} // end if( m_proDialog != null )
    				
    				String str = (String)_msg.obj;
	    			Toast.makeText(m_cxt, str , Toast.LENGTH_SHORT).show();
    				break;
    			}
    			
    			case HANDLER_EVT_ON_PARSE:
    			{
    				compare();
    				break;
    			}
    			
    			case HANDLER_EVT_ON_COMPARE_DONE:
    			{
    				m_proDialog.dismiss();
    				int nMatchCnt = (Integer)_msg.obj;
    				
    				rank(nMatchCnt);
    				
    				break;
    			}
    				
    		} // end switch( nWhat )
		}
	};
	
	private class BtnOnClickListener implements View.OnClickListener
	{
		public void onClick(View _view)
		{
			Button btn = (Button)_view;
			int nID = btn.getId();
			
			switch( nID )
			{
				case R.id.btn_id_input:
				{
					if( m_edtTurn.getText().length() > 0 )
					{
						int nVal = Integer.valueOf(m_edtTurn.getText().toString());
						if( nVal > m_nLastTurn )
						{
							m_edtTurn.setText("");
							m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_TOAST, m_cxt.getString(R.string.str_dialog_error_no_range)));
						} // end if( nVal > m_nLastTurn )
						
						else
						{
							openInputNumberDialog();
						} // end else
					} // end if( m_edtTurn.getText().length() > 0 )
					
					else
					{
						m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_TOAST, m_cxt.getString(R.string.str_dialog_error_no_range)));
					} // end else
					
					break;
				}
			} // end switch( nID )
			
		}
		
	}
	
	private void rank( int _nMatchCnt )
	{
		String strTitle = "";
		String strBody = "";
		
		if( _nMatchCnt < 3 )
		{
			strTitle = getString(R.string.str_loose_title);
			strBody = new Formatter().format(getString(R.string.str_loose_body), _nMatchCnt).toString();
		} // end if( _nMatchCnt < 3 )
		
		else
		{
			strTitle = getString(R.string.str_win_title);
			StringBuilder strB = new StringBuilder();
			
			switch(_nMatchCnt)
			{
				case 3:
				{
					strB.append(new Formatter().format(getString(R.string.str_rank_is), 5).toString()); 
					strB.append("\n");
					strB.append(new Formatter().format(getString(R.string.str_ranker_is), m_lParser.get5thWinnerCnt()).toString());
					strB.append("\n");
					strB.append(new Formatter().format(getString(R.string.str_win_money_is), m_lParser.get5thWinnerMoney()).toString());
					break;
				}
				
				case 4:
				{
					strB.append(new Formatter().format(getString(R.string.str_rank_is), 4).toString());
					strB.append("\n");
					strB.append(new Formatter().format(getString(R.string.str_ranker_is), m_lParser.get4thWinnerCnt()).toString());
					strB.append("\n");
					strB.append(new Formatter().format(getString(R.string.str_win_money_is), m_lParser.get4thWinnerMoney()).toString());
					break;
				}
				
				case 5:
				{
					if( hasBonusNumber() == false )
					{
						strB.append(new Formatter().format(getString(R.string.str_rank_is), 3).toString());
						strB.append("\n");
						strB.append(new Formatter().format(getString(R.string.str_ranker_is), m_lParser.get3rdWinnerCnt()).toString());
						strB.append("\n");
						strB.append(new Formatter().format(getString(R.string.str_win_money_is), m_lParser.get3rdWinnerMoney()).toString());
					} // end if( hasBonusNumber() == false )
					
					else
					{
						strB.append(new Formatter().format(getString(R.string.str_rank_is), 2).toString());
						strB.append("\n");
						strB.append(new Formatter().format(getString(R.string.str_ranker_is), m_lParser.get2ndWinnerCnt()).toString());
						strB.append("\n");
						strB.append(new Formatter().format(getString(R.string.str_win_money_is), m_lParser.get2ndWinnerMoney()).toString());
					} // end else
					
					break;
				}
				
				case 6:
				{
					strB.append(new Formatter().format(getString(R.string.str_rank_is), 1).toString());
					strB.append("\n");
					strB.append(new Formatter().format(getString(R.string.str_ranker_is), m_lParser.get1stWinnerCnt()).toString());
					strB.append("\n");
					strB.append(new Formatter().format(getString(R.string.str_win_money_is), m_lParser.get1stWinnerMoney()).toString());
					break;
				}
			} // end switch(_nMatchCnt)
			
			strBody = strB.toString();
			
		} // end else
		
		new AlertDialog.Builder(this).setTitle(strTitle).setMessage(strBody).setPositiveButton( getString(R.string.str_dialog_btn_ok) , null).show();
	}
	
	private boolean hasBonusNumber()
	{
		NumberInfo nInfo = m_arrLstInfo.get(m_nSelIdx);
		int nLen = nInfo.m_arrLst.size();
		
		int nTmp = Integer.valueOf(m_lParser.getBonusBall());
		int nTmp2 = 0;
		
		for( int i = 0 ; i < nLen ; i++ )
		{
			nTmp2 = Integer.valueOf(nInfo.m_arrLst.get(i));
			
			if( nTmp == nTmp2 )
			{
				return true;
			} // end if( nTmp == nTmp2 )
			
		} // end for( int i = 0 ; i < nLen ; i++ )
		
		return false;
	}
	
	private void compare()
	{
		new Thread(new Runnable()
		{
			public void run()
			{
				NumberInfo nInfo = m_arrLstInfo.get(m_nSelIdx);
				
				if( m_lParser.getTurn().compareTo(nInfo.m_strTurn) == 0 )
				{
					String[] strArr = { m_lParser.get1stBall() , m_lParser.get2ndBall() , m_lParser.get3rdBall() , m_lParser.get4thBall() , m_lParser.get5thBall() , m_lParser.get6thBall() };
					int nSize = strArr.length;
					int nMatchedNumberCnt = 0;
					
					int nTmp = 0;
					int nTmp2  = 0;
					for( int i = 0 ; i < nSize ; i++ )
					{
						nTmp = Integer.valueOf(strArr[i]);
						
						for( int j = 0 ;  j < nSize ; j++ )
						{
							nTmp2 = Integer.valueOf(nInfo.m_arrLst.get(j));
							if( nTmp == nTmp2 )
							{
								nMatchedNumberCnt++;
								break;
							} // end if( nTmp == nTmp2 )
							
						} // end for( int j = 0 ;  j < nSize ; j++ )
						
					} // end for( int i = 0 ; i < nSize ; i++ )
					
					m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_COMPARE_DONE, nMatchedNumberCnt));
					
				} // end if( m_lParser.getTurn().compareTo(nInfo.m_strTurn) == 0 )
				
			}
			
		}).start();
	}
	
	private void parseLotto( final String _str )
	{
		if( m_lParser == null )
		{
			m_lParser = new LottoParser();
		} // end if( m_lParser == null )
		else
		{
			m_lParser.clear();
		} // end else
		
		m_lParser.setData(_str);
		
		new Thread(new Runnable()
		{
			public void run()
			{
				m_lParser.parse();
				m_handler.sendEmptyMessage(HANDLER_EVT_ON_PARSE);
			}
		}).start();
	}
	
	private void openInputNumberDialog()
	{
		final LinearLayout linDialog = (LinearLayout)View.inflate(this, R.layout.lottoinformation_dialog_check_my_number , null);
		final TextView[] txtArr = { (TextView)linDialog.findViewById(R.id.txt_id_1) , (TextView)linDialog.findViewById(R.id.txt_id_2) , (TextView)linDialog.findViewById(R.id.txt_id_3) ,
									(TextView)linDialog.findViewById(R.id.txt_id_4) , (TextView)linDialog.findViewById(R.id.txt_id_5) , (TextView)linDialog.findViewById(R.id.txt_id_6)};
		
		final ArrayList<String> arrList = new ArrayList<String>();
		
		final Button btnDelete = (Button)linDialog.findViewById(R.id.btn_id_delete_item);
		
		btnDelete.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				int nSize = arrList.size();
				
				if( nSize > 0 )
				{
					int nIdx = nSize - 1;
					txtArr[nIdx].setText("");
					arrList.remove(nIdx);
					
					if( arrList.size() == 0 )
					{
						btnDelete.setVisibility(View.INVISIBLE);
					} // end if( arrList.size() == 0 )
					
				} // end if( nSize > 0 )
			}
		});
		
		final GridView gdView = (GridView)linDialog.findViewById(R.id.grid_id_btns);
		gdView.setAdapter(new GridViewAdapter());
		gdView.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> _parent, View _view, int _nPos, long _lID)
			{
				final TextView txt = (TextView)_view;
				final String strSel = txt.getText().toString();
				
				if( arrList.size() >= txtArr.length )
				{
					return;
				} // end if( arrList.size() >= txtArr.length )
				
				if( arrList.contains(strSel) == true )
				{
					m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_TOAST, m_cxt.getString(R.string.str_has_same_number)));
					return;
				} // end if( arrList.contains(strSel) == true )
				
				else
				{
					arrList.add(strSel);
				} // end else
				
				int nIdx = arrList.size() - 1;
				
				txtArr[nIdx].setText(arrList.get(nIdx));
				
				btnDelete.setVisibility(View.VISIBLE);
			}
			
		});
		new AlertDialog.Builder(this).setTitle(getString(R.string.str_title_check_my_number)).setView(linDialog).setPositiveButton(getString(R.string.str_dialog_btn_ok),  new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface _dialog, int _whichBtn)
			{
				m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_INSERT, arrList));
			}
			
		}).show();
	}
		
	private class GridViewAdapter extends BaseAdapter
	{
		public int getCount()
		{
			return 45;
		}

		public Object getItem(int _nPos)
		{
			return null;
		}

		public long getItemId(int _nPos)
		{
			return _nPos;
		}

		public View getView(int _nPos, View _convertView, ViewGroup _parent)
		{
			TextView txt;
			
			if( _convertView == null )
			{
				txt = new TextView(m_cxt);
				txt.setLayoutParams(new GridView.LayoutParams((int)DisplayUtil.pxTodip(m_cxt, 45),(int)DisplayUtil.pxTodip(m_cxt, 45)));
				txt.setGravity(Gravity.CENTER);
			} // end if( _convertView == null )
			
			else
			{
				txt = (TextView)_convertView;
			} // end else
			
			txt.setText(String.valueOf(_nPos+1));
			txt.setBackgroundColor(0xff323232);
			return txt;
		}
	}
	
	private class CheckMyNumbersAdapter extends BaseAdapter
	{
		private ArrayList<NumberInfo> m_arrLst;
		
		public CheckMyNumbersAdapter( ArrayList<NumberInfo> _arrLst )
		{
			m_arrLst = _arrLst;
		}
		
		public int getCount()
		{
			return m_arrLst.size();
		}

		public NumberInfo getItem(int _nPos)
		{
			return m_arrLst.get(_nPos);
		}

		public long getItemId(int _nPos)
		{
			return _nPos;
		}

		public View getView(final int _nPos, View _convertView, ViewGroup _parent)
		{
			View v;
			
			if( _convertView == null )
			{
				LayoutInflater inflater = (LayoutInflater)m_cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				
				v = inflater.inflate(R.layout.checknumberlistitem_layout, _parent , false);
			} // end if( _convertView == null )
			
			else
			{
				v = _convertView;
			} // end else
		
			if( m_arrLst != null )
			{
				TextView txtTurn = (TextView)v.findViewById(R.id.txt_id_turn);
				TextView txtNumber = (TextView)v.findViewById(R.id.txt_id_number);
				Button btnCheck = (Button)v.findViewById(R.id.btn_id_check);
				
				txtTurn.setText(m_arrLst.get(_nPos).m_strTurn + m_cxt.getString(R.string.str_input_turn));
				
				StringBuilder strB = new StringBuilder();
				
				for( String str : m_arrLst.get(_nPos).m_arrLst ) 
				{
					strB.append(str);
					strB.append(",");
				} // end for( String str : m_arrLst.get(_nPos).m_arrLst )
				
				strB.deleteCharAt(strB.length()-1);
				
				txtNumber.setText(strB.toString());
				
				btnCheck.setOnClickListener(new Button.OnClickListener()
				{
					public void onClick(View arg0)
					{
						m_handler.sendMessage(m_handler.obtainMessage(HANDLER_EVT_ON_CHECK_WIN, _nPos));
					}
				});
				
			} // end if( m_arrLst != null )
			
			return v;
		}
	}
	
	private class NumberInfo
	{
		public String m_strTurn;
		public ArrayList<String> m_arrLst;
		
		public NumberInfo( String _strTurn , ArrayList<String> _arrLst )
		{
			m_strTurn = _strTurn;
			m_arrLst = _arrLst;
		}
	}
}
